
class TModbus:
    def __init__(self):
        pass
    @staticmethod
    def crc16_general(data):
        crc = 0xFFFF
        for byte in data:
            crc ^= byte
            for _ in range(8):
                if crc & 0x0001:
                    crc = (crc >> 1) ^ 0xA001
                else:
                    crc = crc >> 1
        return crc  
    @staticmethod
    def getReadCmdBytes ( unitId , funCode , regAddr , regNum ):
        cmd = []
        try:
            regAddrBytes = (regAddr).to_bytes( 2 , byteorder='big')
            regNumBytes = (regNum).to_bytes( 2 , byteorder='big')
            cmd=[
                unitId ,
                funCode ,
                regAddrBytes[0] ,
                regAddrBytes[1] ,
                regNumBytes[0] ,
                regNumBytes[1] ,
            ]
            crc  = TModbus.crc16_general(bytearray(cmd))
            crcBytes = (crc).to_bytes(2 , byteorder='little')
            cmd.append(crcBytes[0])
            cmd.append(crcBytes[1])

        except Exception as er:
            print(er)
        res = bytearray(cmd)
        return res
    @staticmethod
    def isResponsePgk ( dataBytes ):
        res = False
        try:
            if len(dataBytes)>5:
                dataLen = dataBytes[2]
                res = dataLen + 5 == len(dataBytes)
        except Exception as er:
            print(er)
        return res
